package com.tintintech.sendmail;

import java.io.IOException;
import com.tintintech.sendmail.Config;
import com.tintintech.sendmail.helper.DataHelper;
import com.tintintech.sendmail.util.MailStat;
import com.tintintech.sendmail.util.MailStore;
import com.tintintech.monkey.Acceptor;
import com.tintintech.monkey.codec.scgi.SCGICodecFactory;

public class MailServer {

    public static void main(final String[] args)
    {
        
        /**
         * 多线程使用DataHelper.DB.delete 报错，系统重启后先清空已成功发送的邮件
         */
        String conf = System.getProperty(Config.CONFIG_NAME);
        if (conf == null)
        {
            conf = "F:\\imobile\\tintintech\\sendmail\\trunk\\src\\main\\conf\\local_config.xml";
        }
        Config.loadFile(conf).buildGlobals();
        /*
        String logFile = System.getProperty(Config.LOG_NAME);
        if (logFile == null) {
        	logFile = "F:\\imobile\\tintintech\\sendmail\\trunk\\src\\main\\conf\\log4j.properties";
        }
        PropertyConfigurator.configure(logFile);
        Logger log = Logger.getLogger(MailServer.class);
        log.warn("This is Warning");
        log.debug("This is debug");
        log.info("This is Info");
        */
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run(){
            	MailStat.sync();
            	DataHelper.DB.close();
            }
        });
        MailStat.START_TIMESTAMP = System.currentTimeMillis();
        DataHelper.DB.dropDatabase(MailStore.DB_NAME);
        PutMailboxTask.start();
        
        String listenIp   = System.getProperty("ip");
        String listenPort = System.getProperty("port");
        int port  = 6666;

        if (listenPort != null)
        {
            port = new Integer(listenPort).intValue();
        }

        try {

            System.out.println("Sendmail Server started!");
            new Acceptor(listenIp, port, new SCGICodecFactory(), new MailHandler()).run();
        } catch (final IOException e) {
            e.printStackTrace();
            System.exit(-3);
        }
    }
}
